//
//  Arrays.swift
//  JXBaseTools
//
//  Created by godox on 2021/11/30.
//

import UIKit

extension Array: JXCompatible{}

extension JX where Base == Array<Any>{
    
    /// 交换元素
    public func exchangeValue<T>(_ nums: inout [T], _ a: Int, _ b: Int) {
        (nums[a], nums[b]) = (nums[b], nums[a])
    }
    
    /// 去除数组中重复的model属性
    public func filterDuplicates<E: Equatable>(_ filter: (E) -> E) -> [E] {
        var result = [E]()
        for value in self.base as! [E]
        {
            let key = filter(value)
            if !result.map({filter($0)}).contains(key) {
                result.append(value)
            }
        }
        return result
    }
    
}

extension Array where Element: Equatable {
    @discardableResult
    public mutating func removeObject(newElement: Element) -> Array {
        for (index, item) in self.enumerated() {
            if item == newElement {
                self.remove(at: index)
            }
        }
        return self
    }
}

extension Array where Element: Hashable {
    
    /// 无序去重
    public var duplicates: [Element] {
        let set = Set(self)
        return Array(set)
    }
    /// 有序去重
    public var orderedDuplicates: [Element] {
        var uniqueElements = [Element]()
        var encountered = Set<Element>()
        for element in self {
            if !encountered.contains(element) {
                uniqueElements.append(element)
                encountered.insert(element)
            }
        }
        return uniqueElements
    }
}
